package com.blast.comicsisland.utils;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;

import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * author : hg
 * email: 530157892@qq.com
 * 15/6/9.
 */
public class ImageCache {

    private static ImageCache imageCache;

    public static ImageCache getInstant() {
        if (imageCache == null) {
            imageCache = new ImageCache();
        }

        return imageCache;
    }

    /**
     * 强引用缓存区 保证最经常使用的图片不被回收
     */
    private LruCache<String, Bitmap> lruCache;

    /**
     * 弱引用缓存区
     */
    private HashMap<String, SoftReference<Bitmap>> mapCache;

    private ImageCache() {

        mapCache = new HashMap<String, SoftReference<Bitmap>>();

        //获取应用程序已经得到的内存大小
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();

        //设置强引用所使用的内存大小
        lruCache = new LruCache<String, Bitmap>((int) (totalMemory / 4)) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getHeight() * value.getRowBytes();
            }
        };
    }

    /**
     * 获取内存中的Bitmap
     *
     * @param url
     * @return
     */
    public Bitmap get(String url) {
        Bitmap ret = null;
        if (url != null) {
            //检查强引用有没有数据 有旧返回
            ret = lruCache.get(url);
            Log.d("ImageCache", "lruCache Item:" + ret);
            if (ret == null) {
                SoftReference<Bitmap> reference = mapCache.get(url);
                if (reference != null) {
                    ret = reference.get();
                }
                if (ret != null) {
                    lruCache.put(url, ret);
                }
            }
        }
        return ret;
    }

    /**
     * 对图片进行内存的缓存
     *
     * @param url
     * @param bitmap
     */
    public void put(String url, Bitmap bitmap) {
        if (url != null && bitmap != null) {
            SoftReference<Bitmap> reference = new SoftReference<Bitmap>(bitmap);
            mapCache.put(url, reference);
            lruCache.put(url, bitmap);
        }


    }


}
